import { useState, useEffect } from 'react';
import { useMCPContext } from '../contexts/MCPContext.tsx';

interface UseMCPToolResult<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

const useMCPTool = <T,>(toolName: string, args?: any): UseMCPToolResult<T> => {
  const { callTool } = useMCPContext();
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const result = await callTool(toolName, args);
        setData(result);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error occurred');
        setData(null);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [toolName, args, callTool]);

  return { data, loading, error };
};

export { useMCPTool };